<template>
  <div>
    <!--快捷下单 -->
    <el-card v-if="orderType === 'quickOrder'" class="box-card margin-bottom">
      <div slot="header" class="clearfix">
        <span class="title-icon">{{ $t('waybill.upExcelTitle') }}</span>
        <span class="text-red margin-left">
          请直接上传从亚马逊卖家后台导出的发货计划表（EXCEL格式）。一键上传，自动完成发票和装箱单填写。如有疑问，请
          <router-link target="_blank" :to="{ name: 'QuickOrderGuidance' }">
            <span class="text-blue"> 点击此处 </span>
            <i class="el-icon-view el-icon--right text-blue" />
          </router-link>
        </span>
      </div>

      <el-row class="flex align-center" :gutter="10">
        <el-col :span="3">
          <span>请上传EXCEL：</span>
          <span class="text-red">*</span>
        </el-col>
        <el-col v-for="(item, index) in fileList" :key="index" :span="3">
          <div class="upload-input pointer">
            <input
              type="file"
              :disabled="item.file ? true : false"
              @change="upload($event, index)"
            >
            {{ item.file ? item.name : index > 0 ? '继续上传' : '选择文件' }}
          </div>
        </el-col>
      </el-row>

      <el-row class="margin-top" :gutter="10">
        <el-col :span="3">
          <span>派送地址：</span>
        </el-col>
        <el-col :span="3">
          {{ address }}
        </el-col>
      </el-row>
    </el-card>
    <!--  -->

    <el-card id="selectChannel" class="box-card">
      <div slot="header" class="clearfix">
        <span class="title-icon">{{ $t('waybill.selectChannel') }}</span>
      </div>
      <el-row>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="padding-40">
          <SelectChannelLeft
            ref="selectChannelLeftComp"
            :order-type="orderType"
            :channel-form-left.sync="channelFormLeft"
            @func="boxList"
          />
        </el-col>
        <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12" class="padding-40">
          <SelectChannelRight
            ref="selectChannelRightComp"
            :customer-shipper-map="customerShipperMap"
            :customer-importer="customerImporter"
            :channel-form-data.sync="channelFormRight"
            :importer-info.sync="selectedImporterInfo"
          />
        </el-col>
      </el-row>
    </el-card>

    <Invoice
      ref="invoice"
      :order-type="orderType"
      :waybill-id="id"
      :waybill-code="randomCode"
      :invoice-table-info.sync="invoiceInfo"
      :show-tips.sync="showTips"
    />

    <PackingList
      v-if="createTpye !== 'OrderToExpressDelivery'"
      ref="packingList"
      :show-tips="showTips"
      :packing-list-info.sync="packingInfo"
      @resetPacking="resetPacking"
    />

    <div class="text-center margin-tb">
      <el-button
        v-if="!id || status === 10 || $route.query.isCopy"
        type="primary"
        @click="submitForm(10)"
      >
        提交待确认
      </el-button>
      <el-button type="primary" @click="submitForm(20)"> 完成并提交 </el-button>
    </div>
  </div>
</template>

<script>
import SelectChannelLeft from './SelectChannelLeft.vue'
import SelectChannelRight from './SelectChannelRight.vue'
import Invoice from './Invoice.vue'
import PackingList from './PackingList.vue'
import { mapGetters } from 'vuex'
import {
  saveWaybillStandard,
  saveWaybillFba,
  doImportPackLists,
  getWaybillById
} from '@/api/waybill'
import { createFbaOrder } from '@/api/amazon'
import { getToken } from '@/utils/auth'
import { clone } from '@/utils/clone'
import { uncompileStr } from '@/utils'
import { isNoEmptyObject, checkRowsEmpty } from '@/utils/waybill-public'
import { customerShipperList } from '@/api/myProfile'
import globalData from '@/utils/config'
export default {
  name: 'TabPane',
  components: {
    SelectChannelLeft,
    SelectChannelRight,
    Invoice,
    PackingList
  },
  props: {
    orderType: {
      type: String,
      default: 'quickOrder'
    }
  },
  data() {
    return {
      status: '',
      address: '',
      id: '',
      customerTotalPackages: 0,
      randomCode: '',
      fileList: [
        {
          file: ''
        }
      ],

      invoicesAndPackingLis: {},
      list: null,
      waybillRender: {},
      fbaRules: ['shipmentId', 'referenceId'],
      rules: [
        'sku',
        'declareNameCn',
        'declareNameEn',
        'brand',
        'material',
        'purpose',
        // 'customsCode',
        'model',
        'num',
        'measurementUnit',
        'purchasingPrice',
        'sku',
        'declareValue',
        'imgUrl'
      ],
      jpRules: [
        'asin',
        'distributionMaterialCount',
        'productLotCount',
        'sellPriceScreenshot',
        'incomeScreenshot'
      ],
      clrRules: {
        senderCompany: '发件人公司名(英)',
        senderCompanyCN: '发件人公司名',
        senderLinkMan: '联系人',
        senderPhone: '电话',
        senderEnterpriseCreditCode: '企业信用代码',
        senderAdress: '详细地址(英)'
      },
      params: {
        shipmentId: 'Shipment ID',
        referenceId: 'Reference ID',
        sku: 'SKU',
        declareNameCn: '中文品名',
        declareNameEn: '英文品名',
        brand: '品牌',
        material: '材质',
        purpose: '用途',
        // customsCode: '出口报关编码',
        customsClearanceCode: '清关编码',
        model: '型号',
        asin: 'ASIN/销售链接',
        num: 'SKU个数',
        measurementUnit: '单位',
        fnSku: 'FNSKU',
        purchasingPrice: '采购价格',
        declareValue: '申报价格',
        imgUrl: 'SKU图片',
        distributionMaterialCount: '配送料',
        productLotCount: '出品手数料',
        sellPriceScreenshot: '售价截图',
        incomeScreenshot: '收益截图'
      },
      packingParams: {
        weight: '单箱毛重',
        length: '单箱长度',
        width: '单箱宽度',
        height: '单箱高度',
        startNumNo: '箱号',
        sku: 'SKU',
        num: 'SKU数量'
      },
      // packingRules: ['startNumNo', 'weight', 'length', 'width', 'height'],
      packingRules: ['startNumNo'],
      customerShipperMap: [],
      customerImporter: [],

      selectedImporterInfo: {},
      channelFormLeft: {},
      channelFormRight: {},
      invoiceInfo: {},
      packingInfo: [],
      showTips: ''
    }
  },

  computed: {
    ...mapGetters(['createTpye', 'publicData', 'name']),
    isJapan() {
      return (
        this.publicData.countryMap &&
        this.channelFormLeft &&
        this.channelFormLeft.countryId &&
        this.publicData.countryMap[this.channelFormLeft.countryId] &&
        this.publicData.countryMap[this.channelFormLeft.countryId].indexOf(
          '日本'
        ) != -1
      )
    },
    isTaxFarming() {
      return this.channelFormLeft.isTaxFarming
    }
  },

  watch: {
    channelFormLeft: {
      handler(val) {},
      immediate: true,
      deep: true
    },
    channelFormRight: {
      handler(val) {},
      immediate: true,
      deep: true
    },
    selectedImporterInfo: {
      handler(val) {},
      immediate: true,
      deep: true
    },
    invoiceInfo: {
      handler(val) {
        console.log('invoiceInfo val :>> ', val)
      },
      immediate: true,
      deep: true
    },
    packingInfo: {
      handler(val) {},
      immediate: true,
      deep: true
    }
    // 'this.$refs.selectChannelLeftComp.channelform': {
    //   handler(val) {
    //     console.log('selectChannelLeftComp watch :>> ', val)
    //   }
    // }
  },
  created() {
    if (this.$route.query.id) {
      const id = uncompileStr(this.$route.query.id)
      this.randomCode = this.$route.query.randomCode
      if (id) {
        this.id = id
        this.getWaybillInfo()
      }
      console.log('this.$route.params :>> ', this.$route.params)
      if (this.$route.params.shipmentId) {
        console.log(
          'this.$route.params.shipmentId :>> ',
          this.$route.params.shipmentId
        )
        this.getWaybillInfo()
      }
    }
  },
  mounted() {
    this.init()
    console.log('this.$refs.invoice.timer :>> ', this.$refs.invoice)
    console.log('this.name :>> ', this.name)
  },
  destroyed() {
    let str = ''
    if (this.id) {
      str = this.id
    } else {
      str = this.randomCode
    }
    sessionStorage.removeItem('channelFormLeft')
    sessionStorage.removeItem(`tableInvoice-${str}`)

    // clearInterval(this.$refs.invoice.timer)
  },
  methods: {
    async init() {
      // this.$store.dispatch('createWaybill/initWaybillRender')
      this.customerShipperMap = await customerShipperList({
        authorization: getToken()
      })
    },

    resetPacking() {
      this.$refs.invoice.resetPacking()
    },
    boxList(val) {
      console.log('val: ', val)
      let strInfo = ''
      const arr = []
      if (val.length > 0) {
        for (const i of val) {
          if (i.cabinetNumber && i.cabinetType) {
            strInfo = i.cabinetNumber + '*' + i.cabinetType
            arr.push(strInfo)
          } else {
            this.$message('请完整填写柜量！')
          }
        }
        const arrJoinString = arr.join(';')
        this.channelFormLeft.cabinetInfo = arrJoinString
      }
    },
    // 数据回显
    getWaybillInfo() {
      this.$store.dispatch('app/toggleDialog', true)

      if (this.orderType === 'AmazonCreateOrder') {
        let arr = []
        if (
          Object.prototype.toString.call(this.$route.params.shipmentId) ===
          '[object Array]'
        ) {
          arr = this.$route.params.shipmentId
        } else {
          arr.push(this.$route.params.shipmentId)
        }
        createFbaOrder(arr).then((res) => {
          if (res.code === 200) {
            this.setOrderDate(res)
          } else {
            this.$message.error(res.message || '系统错误')
            window.history.length > 1
              ? this.$router.go(-1)
              : this.$router.push('/pages/amazon/planList')
            return
          }
        })
      } else {
        if (this.id !== null) {
          getWaybillById({
            id: parseInt(this.id)
          }).then((res) => {
            if (res.code && res.code === 500) {
              this.$message.error(res.message || '获取订单信息失败！')
              this.$store.dispatch('app/toggleDialog', false)
              this.$router.push('/')
              return
            }
            this.setOrderDate(res)
          })
        }
      }
    },

    async setOrderDate(res) {
      const waybill = res.data.waybill
      const liquidationInvoiceList = res.data.liquidationInvoiceList
      this.status = waybill.status

      const arr = waybill.cabinetInfo
        ? waybill.cabinetInfo.split(';')
        : ['', '']

      let cabinetInfo = []
      this.$refs.selectChannelLeftComp.boxMap = []
      if (arr.length > 0) {
        for (const k of arr) {
          cabinetInfo = k.split('*')
          this.$refs.selectChannelLeftComp.boxMap.push({
            cabinetNumber: parseInt(cabinetInfo[0]), // 柜量
            cabinetType: cabinetInfo[1] // 柜型
          })
        }
      }

      this.$refs.selectChannelLeftComp.channelform = {
        purposeWarehouseType: waybill.purposeWarehouseType || '', //  目的仓库类型
        customerRemark: waybill.customerRemark || '', // 运单备注
        loadingPort: waybill.loadingPort ? waybill.loadingPort.toString() : '', // 起运地
        countryId: waybill.countryId ? waybill.countryId.toString() : '', //  国家
        customerActualWeight: waybill.customerActualWeight || '', //  重量
        customerTotalPackages: waybill.customerTotalPackages || '', // 件数
        customerVolume: waybill.customerVolume || '', //  体积
        dispatchAddressCode: waybill.dispatchAddressCode || '', // 地址
        channelCapacity: waybill.channelCapacity
          ? waybill.channelCapacity.split(',')
          : [], //  渠道能力
        specialProduct: waybill.specialProduct
          ? waybill.specialProduct.split(',')
          : [], //  特殊产品
        isTaxFarming: waybill.isTaxFarming, // 是否包税
        isChinaAustraliaCard: waybill.isChinaAustraliaCard, // 是否包税
        deliveryTerms: waybill.deliveryTerms, //  交货条款

        provinceId: waybill.provinceId ? waybill.provinceId.toString() : '', //  国内分区
        inStockChannel: waybill.inStockChannel, //  渠道
        deliveryNumber: waybill.deliveryNumber || '', //  渠道
        deliveryWay: waybill.deliveryWay || '', // 提货方式
        isBuyInsurance: waybill.isBuyInsurance, // 保险
        selfDelivered: waybill.selfDelivered, //
        dispatcher: waybill.dispatcher || '', // 公司名/个人
        dispatchLinkMan: waybill.dispatchLinkMan || '', //  联系人
        dispatchPhone: waybill.dispatchPhone || '', //  联系电话
        dispatchEmail: waybill.dispatchEmail || '', //  邮箱
        dispatchProvince: waybill.dispatchProvince || '', //  省
        dispatchCity: waybill.dispatchCity || '', //  城市
        dispatchZipCode: waybill.dispatchZipCode || '', //  邮编
        dispatchAddress: waybill.dispatchAddress || '', //  地址
        dispatchAddress2: waybill.dispatchAddress2 || '', //  地址
        shippingWay: waybill.shippingWay || '', //  海空运下单方式
        // deliveryType: waybill.deliveryType || '', //  派送方式
        isPVA: waybill.isPVA || '', //  Postponed VAT Accounting/增值税递延
        etInStock: waybill.etInStock || '',
        customerChargedWeight: waybill.customerChargedWeight
      }
      if (waybill.extraAttributes) {
        if (
          Object.prototype.toString.call(waybill.extraAttributes) ===
          '[object Array]'
        ) {
          const obj = {}
          for (const i of waybill.extraAttributes) {
            obj[i] = i
          }
          this.$refs.selectChannelLeftComp.channelform.extraAttributes = obj
        } else if (
          Object.prototype.toString.call(waybill.extraAttributes) ===
          '[object Object]'
        ) {
          this.$refs.selectChannelLeftComp.channelform.extraAttributes =
            waybill.extraAttributes
        }
      }
      if (waybill.deliveryFiles) {
        if (
          Object.prototype.toString.call(waybill.deliveryFiles) ===
          '[object Array]'
        ) {
          const obj = {}
          if (waybill.deliveryFiles.length > 0) {
            for (const i of waybill.deliveryFiles) {
              const arr = i.split(',')
              console.log('arr :>> ', arr)
              obj[arr[0]] = arr[1]
            }
          }

          console.log('obj :>> ', obj)
          this.$refs.selectChannelLeftComp.channelform.deliveryFilesMap = obj
        }
      }

      if (waybill.isPVA !== null) {
        this.$refs.selectChannelLeftComp.channelform.isPVA = waybill.isPVA
      }

      if (waybill.deliveryType) {
        this.$refs.selectChannelLeftComp.channelform.deliveryType =
          waybill.deliveryType
      }

      this.$refs.selectChannelLeftComp.channelform.isCustomerDeclaration =
        waybill.isCustomerDeclaration
      console.log('waybill.etInStock :>> ', waybill.etInStock)
      // 入仓时间
      if (waybill.etInStock) {
        const etInStock = waybill.etInStock.split(' ')
        console.log('etInStock :>> ', etInStock)
        this.$refs.selectChannelLeftComp.etInStockDay = etInStock[0]
        this.$refs.selectChannelLeftComp.etInStockTime = etInStock[1]
      }

      if (!waybill.custoemrSenderId) {
        this.$refs.selectChannelRightComp.SenderCompanyType = false
      }

      this.$refs.selectChannelRightComp.channelformRight = {
        referenceNo: waybill.referenceNo,
        custoemrSenderId: waybill.custoemrSenderId,
        senderCompany: waybill.senderCompany,
        senderCompanyCN: waybill.senderCompanyCN,
        senderLinkMan: waybill.senderLinkMan,
        senderPhone: waybill.senderPhone,
        senderZipCode: waybill.senderZipCode,
        senderEnterpriseCreditCode: waybill.senderEnterpriseCreditCode,
        senderAdress: waybill.senderAdress,
        shipperAttn: waybill.senderLinkMan,
        shipperPhone: waybill.senderPhone,
        shipperAddress: waybill.senderAdress,
        isVatAndEori: waybill.isVatAndEori,
        isJiufangImporter: waybill.isJiufangImporter
      }
      this.$refs.selectChannelRightComp.selectedImporterInfo = {
        importerAddress: waybill.importerAddress,
        importerCompanyName: waybill.importerCompanyName,
        importerLinkMan: waybill.importerLinkMan,
        importerPhone: waybill.importerPhone,
        importerZipCode: waybill.importerZipCode,
        vat: waybill.vat,
        eori: waybill.eori
      }

      this.sortData({
        declareValueCurrency: waybill.declareValueCurrency,
        liquidationInvoices: liquidationInvoiceList,
        packingLists: res.data.packingListmMap
      })

      await this.$refs.selectChannelLeftComp.retrieveAddress('edit')
      await this.$refs.selectChannelLeftComp.retrieveChannel('edit')
    },

    async sortData(waybill) {
      console.log('waybill :>> ', waybill)
      if (waybill.declareValueCurrency) {
        setTimeout(() => {
          this.$refs.invoice.invoiceInfoData.declareValueCurrency = clone(waybill.declareValueCurrency)
        }, 2000)
      }
      // invoice
      if (waybill.liquidationInvoices.length > 0) {
        const d = clone(waybill.liquidationInvoices)
        for (const i of d) {
          if (i.sellpriceScreenshot) {
            i.sellPriceScreenshot = i.sellpriceScreenshot
          }
        }
        console.log('d :>> ', d)
        this.$refs.invoice.invoiceInfoData.tableData = clone(d)
        this.$refs.invoice.invoiceInfoData.oldTableData = clone(d)
        console.log('this.$refs.invoice :>> ', this.$refs.invoice)
        console.log(
          'this.$refs.invoice.invoiceInfoData :>> ',
          this.$refs.invoice.invoiceInfoData
        )
        this.$store.dispatch(
          'createWaybill/changeInvoiceInfo',
          this.$refs.invoice.invoiceInfoData
        )
      }

      // 同步箱单
      if (
        this.createTpye !== 'OrderToExpressDelivery' &&
        waybill.liquidationInvoices.length > 0
      ) {
        if (waybill.packingLists) {
          // 存在箱单信息
          console.log('上传信息存在箱单信息')
          this.$refs.invoice.IntegratePackingData(waybill.packingLists)
        } else {
          // 不存在箱单信息 根据发票生成
          console.log('上传信息不存在箱单信息')
          this.$refs.invoice.IntegrateInvoiceData()
        }
      }
      this.$store.dispatch('app/toggleDialog', false)
    },

    // 检查货值
    forcedPurchaseInsurance(cl, price) {
      console.log('cl :>> ', cl)
      console.log('price :>> ', price)
      const t = (price * 100) / (cl.customerActualWeight * 100)
      console.log('t :>> ', t)

      return new Promise((resolve, reject) => {
        if (t > 1000) {
          cl.superHighValue = 1
          const h = this.$createElement
          this.$msgbox({
            title: '提示',
            message: h('div', null, [
              h('p', null, '您的货值已经超过RMB1000/KG,建议您选择投保！'),
              h(
                'p',
                null,
                '投保：保费收取货值0.4%,货损赔偿(货值+运费)90%,最高上限RMB1000/KG; '
              ),
              h(
                'p',
                null,
                '不投保：货物丢失赔偿按照(货值+运费)90%,最高上限RMB300/KG'
              )
            ]),
            showCancelButton: true,
            confirmButtonText: '投保',
            cancelButtonText: '不投保'
          })
            .then(() => {
              cl.isBuyInsurance = 1
              resolve(cl)
            })
            .catch(() => {
              cl.isBuyInsurance = 0
              resolve(cl)
            })
        } else {
          cl.superHighValue = 0
          resolve(cl)
        }
      })
    },

    async submitForm(status) {
      const cl = this.$refs.selectChannelLeftComp.channelform
      // -------------------------------------------------------------------------------- 派送地址拼接
      if (this.orderType === 'quickOrder') {
        console.log('cl :>> ', cl)
        if (!cl.dispatchAddressCode) {
          this.$message.error(
            '派送地址仓库代码不存在,请确认上传的入库计划装箱单是否配置FBA仓库信息'
          )
          return false
        }
        if (!cl.dispatcher) {
          this.$message.error(
            '派送地址公司不存在,请确认上传的入库计划装箱单是否配置FBA仓库信息'
          )
          return false
        }
        if (!cl.dispatchAddress) {
          this.$message.error(
            '派送地址不存在,请确认上传的入库计划装箱单是否配置FBA仓库信息'
          )
          return false
        }
        if (!cl.dispatchCity) {
          this.$message.error(
            '派送地址城市不存在,请确认上传的入库计划装箱单是否配置FBA仓库信息'
          )
          return false
        }
        if (!cl.dispatchProvince) {
          this.$message.error(
            '派送地址州省不存在,请确认上传的入库计划装箱单是否配置FBA仓库信息'
          )
          return false
        }
        if (!cl.dispatchZipCode) {
          this.$message.error(
            '派送地址邮编不存在,请确认上传的入库计划装箱单是否配置FBA仓库信息'
          )
          return false
        }
      }

      if (!this.checkChannelLetf()) {
        return false
      }
      if (!this.checkChannelRtight()) {
        return false
      }

      if (!this.checkInvoice(status)) {
        return false
      }
      // 箱单信息
      const plist = []
      const skuList = []
      console.log(this.packingInfo)
      for (const i of this.packingInfo) {
        for (const j of i.tableData) {
          const obj = {
            waybillId: '',
            shipmentId: j.shipmentId,
            startNumNo: j.cartonNo,
            endNumNo: j.cartonNo,
            length: j.length,
            width: j.width,
            height: j.height,
            weight: j.grossWeight,
            remark: j.remark,
            packSkuList: [
              {
                sku: j.skuName,
                declareNameCn: j.declareNameCn,
                declareNameEn: j.declareNameEn,
                num: j.skuNum
              }
            ]
          }
          plist.push(obj)
        }
        if (status === 20 && i.filterData) {
          for (const k of i.filterData) {
            skuList.push(k)
          }
        }

        if (i.tableData.length > 0 && !i.filterData) {
          this.$message.error(
            '装箱单数据与发票数据匹配失败，请重置装箱单，或者重新导入箱单发票'
          )
          return
        }
      }
      console.log('plist ', plist)

      const packingList = plist.reduce((pVal, cVal) => {
        const target = pVal.find((x) => x.startNumNo === cVal.startNumNo)
        if (target) {
          // 相同sku 合并数量
          target.packSkuList = [...target.packSkuList, ...cVal.packSkuList]
        } else {
          pVal.push(cVal)
        }
        return pVal
      }, [])

      console.log('packingList :>> ', packingList)

      if (status === 20 && !this.checkPackingInfo(packingList, skuList)) {
        return false
      }

      // 件数需要与装箱数相等  快递除外
      if (
        status === 20 &&
        this.createTpye !== 'OrderToExpressDelivery' &&
        this.channelFormLeft.customerTotalPackages !== packingList.length
      ) {
        this.$message.error('客户下单件数和装箱单数量不匹配')
        return
      }

      this.saveWaybill({ status, packingList })
    },
    checkChannelLetf() {
      let flag = true

      const cl = this.$refs.selectChannelLeftComp.channelform
      this.$refs.selectChannelLeftComp.$refs.channelform.validate((valid) => {
        if (valid) {
          if (
            (cl.countryId === '339' ||
              cl.countryId === '329' ||
              cl.countryId === '332') &&
            cl.purposeWarehouseType === 700 &&
            cl.dispatchProvince.length > 3
          ) {
            this.$message.error('州/省长度不可以大于3')
            flag = false
          } else {
            flag = true
          }
        } else {
          this.$message.error('请补充渠道信息')
          flag = false
        }
      })
      return flag
    },
    checkChannelRtight() {
      let formright = false

      const clr = this.$refs.selectChannelRightComp.channelformRight

      if (!clr.custoemrSenderId) {
        for (const i in this.clrRules) {
          if (!clr[i]) {
            console.log('clr[i] :>> ', clr[i])
            this.$message.error(`请填写${this.clrRules[i]}`)
            return
          }
        }
        formright = true
      } else {
        formright = true
      }

      if (!formright) return false
      // 自有VAT和EORI，一定要选进口商
      if (
        this.channelFormRight.isVatAndEori === 1 &&
        (clr.isJiufangImporter === 0 ||
          clr.isJiufangImporter === null ||
          clr.isJiufangImporter === undefined) &&
        JSON.stringify(this.selectedImporterInfo) === '{}'
      ) {
        this.$message.error('请选择进口商')

        return false
      }
      if (
        clr.isJiufangImporter &&
        clr.isJiufangImporter !== null &&
        clr.isJiufangImporter !== undefined
      ) {
        this.selectedImporterInfo.importerCompanyName = 'JIUFANG'
        this.selectedImporterInfo.importerLinkMan = '九方'
        this.selectedImporterInfo.importerPhone = '九方'
        this.selectedImporterInfo.vat = '九方'
        this.selectedImporterInfo.eori = '九方'
        this.selectedImporterInfo.importerAddress = '九方'
        this.selectedImporterInfo.importerZipCode = '九方'
      }

      return true
    },
    checkInvoice(status) {
      const reg = new RegExp(
        '([\u4E00-\u9FFF]|[\u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b\uff01\u3010\u3011\uffe5])+',
        'g'
      )
      const numReg = /^\d+$|^\d*\.\d+$/g
      const numReg2 = /^\d+(\.\d{1,5})?$/
      const isFBA = this.channelFormLeft.purposeWarehouseType === 100

      let rules = [...this.rules]
      if (isFBA && !reg.test(this.channelFormLeft.dispatchAddressCode)) {
        rules = [...this.fbaRules, ...rules]
      }
      if (this.isJapan) {
        if (isFBA && this.createTpye === 'orderToSeaFreight') {
          rules = [...rules, 'fnSku', ...this.jpRules]
        } else {
          rules = [...rules, ...this.jpRules]
        }
      }
      console.log('this.invoiceInfo :>> ', this.invoiceInfo)
      if (status === 20 && !isNoEmptyObject(this.invoiceInfo)) {
        this.$message.error('请填写发票数据！')
        return false
      }

      if (status === 20 && this.invoiceInfo.tableData.length === 0) {
        this.$message.error('请填写发票数据！')
        return false
      }

      const tableData = this.invoiceInfo.tableData.filter((x) =>
        checkRowsEmpty(x)
      )
      if (status === 20 && tableData.length === 0) {
        this.$message.error('请填写发票数据！')
        return false
      }

      console.log('tableData :>> ', tableData)
      for (const [i, e] of tableData.entries()) {
        for (const j of rules) {
          // console.log('e[j] :>> ', e[j])
          if (
            isNoEmptyObject(e) &&
            j === 'distributionMaterialCount' &&
            parseInt(e[j]) === 0
          ) {
            console.log('配送料为0 ')
          } else if (status === 20 && isNoEmptyObject(e) && !e[j]) {
            if (j === 'declareValue' && this.isJapan) {
              this.$message.error(`请填写第${i + 1}行 必填数据 ASIN售价`)
            } else {
              this.$message.error(
                `请填写第${i + 1}行 必填数据 ${this.params[j]}`
              )
            }
            return false
          }
          if (j === 'declareNameEn' && reg.test(e[j])) {
            this.$message.error(
              `请填写第${i + 1}行 必填数据 英文品名 请勿包含中文字符`
            )
            return false
          }
          if (status === 20 && j === 'fnSku' && e[j].length > 10) {
            this.$message.error(`请填写第${i + 1}行 FNSKU 限制10位`)
            return false
          }

          if (
            (j === 'num' ||
              j === 'declareValue' ||
              j === 'purchasingPrice' ||
              j === 'distributionMaterialCount' ||
              j === 'productLotCount') &&
            Object.prototype.toString.call(e[j]) !== '[object Number]'
          ) {
            this.$message.error(
              `第${i + 1}行 必填数据 ${this.params[j]},请填写正确数字`
            )
            return false
          }

          // shipmentId
          if (
            this.channelFormLeft.purposeWarehouseType === 100 &&
            this.name.indexOf('通网供应链') == -1 &&
            !reg.test(this.channelFormLeft.dispatchAddressCode)
          ) {
            if (
              isNoEmptyObject(e) &&
              j === 'shipmentId' &&
              e[j] &&
              (e[j].indexOf('FBA') !== 0 || e[j].length !== 12)
            ) {
              this.$message.error(
                `Shipment ID 错误： FBA+(字母+数字组合)共12位`
              )
              return false
            }
          }

          // measurementUnit

          if (j === 'measurementUnit' && this.publicData.skuUnitMap[e[j]]) {
            if (
              ['套', '包'].includes(e[j]) &&
              Object.prototype.toString.call(e.perSuitNum) !== '[object Number]'
            ) {
              this.$message.error(`第${i + 1}行 每套个数,请填写正确数字`)
              return false
            } else if (['套', '包'].includes(e[j]) && !e.perSuitNum) {
              this.$message.error(
                `请填写第${i + 1}行每套个数,单位为套/包时,每套个数必填`
              )
              return false
            }
          }
          if (j === 'measurementUnit' && !this.publicData.skuUnitMap[e[j]]) {
            this.$message.error(`第${i + 1}行,必填数据 单位，请选择正确的值`)
            return false
          }
        }
        // ASIN 必填校验
        /**
           * 1. 目的国日本必填
           * 2. 目的国比利时必填
           * 3. 以下欧洲包税，如果目的国家是英国，ASIN非必填，其他必填
              欧洲空派带电(包税) AIR-EU-04  id => 15
              欧洲空派普货(包税) AIR-EU-03   id => 13
              欧洲卡铁联运&欧洲卡车TIR（包税） TIR-EU-01   id=> 215
            * 4.渠道名称 含比利时，ASIN必填
              欧洲卡铁联运&欧洲卡车TIR（比利时不包税） TIR-EU-03
              比利时空派普货(不包税) AIR-BE-01
              比利时空派带电(不包税) AIR-BE-02
              比利时整柜                   FCL-BE
              比利时卡派不包税         LCL-BE-K
           */
        if (status === 20 && !e.asin) {
          const list = [15, 13, 215]

          if (
            this.channelFormLeft.countryId === 353 ||
            this.publicData.channelMap[
              this.channelFormLeft.inStockChannel
            ].indexOf('比利时') > -1 ||
            (list.includes(this.channelFormLeft.inStockChannel) &&
              this.channelFormLeft.countryId !== 330)
          ) {
            this.$message.error(`请填写第${i + 1}行 必填数据 ASIN/销售链接`)
            return false
          }
        }

        if (this.isTaxFarming !== 1 && !e.customsCode) {
          this.$message.error(`请填写第${i + 1}行 必填数据 报关编码`)
          return false
        }
        if (this.isTaxFarming !== 1 && !e.customsClearanceCode) {
          this.$message.error(`请填写第${i + 1}行 必填数据 清关编码`)
          return false
        }

        const regCode = /^\d+$|^\d*\.\d+$/g
        if (e.customsCode && !regCode.test(e.customsCode)) {
          this.$message.error(`第${i + 1}行  报关编码只能输入数字和“.”`)
          return
        }
        const regCode1 = /^\d+$|^\d*\.\d+$/g
        if (e.customsClearanceCode && !regCode1.test(e.customsClearanceCode)) {
          this.$message.error(`第${i + 1}行  清关编码只能输入数字和“.”`)
          return
        }

        // if (e.customsCode && !numReg.test(e.customsCode)) {
        //   this.$message.error(`第${i + 1}行 必填数据 报关编码 请正确填写`)
        //   return
        // }
        // if (e.customsClearanceCode && !numReg.test(e.customsClearanceCode)) {
        //   this.$message.error(`第${i + 1}行 必填数据 清关编码 请正确填写`)
        //   return
        // }
        if (e.purchasingPrice && !numReg2.test(parseFloat(e.purchasingPrice))) {
          this.$message.error(`第${i + 1}行 必填数据 采购单价 只能输入大于等于0.00001的正数`)
          return
        }
        if (e.declareValue && !numReg2.test(parseFloat(e.declareValue))) {
          this.$message.error(`第${i + 1}行 必填数据 申报单价 只能输入大于等于0.00001的正数`)
          return
        }
      }
      return true
    },

    checkPackingInfo(packingList, skuList) {
      // 校验箱单
      if (this.createTpye !== 'OrderToExpressDelivery' && packingList) {
        console.log('packingList :>> ', packingList)
        console.log('skuList :>> ', skuList)
        if (packingList.length === 0) {
          this.$message.error(`请填写装箱单`)
          return false
        }
        for (const [i, e] of packingList.entries()) {
          for (const j of this.packingRules) {
            if (isNoEmptyObject(e) && !e[j]) {
              this.$message.error(
                `请填写箱号${e.startNumNo}  ${this.packingParams[j]}`
              )
              return false
            }
          }
          for (const k of e.packSkuList) {
            if (!k.sku) {
              this.$message.error(`请填写箱号${e.startNumNo} SKU`)
            }
            if (!k.num) {
              this.$message.error(`请填写箱号${e.startNumNo} SKU数量`)
            }
          }
        }

        for (const i of skuList) {
          if (parseInt(i.skuNum) !== parseInt(i.packingNum)) {
            this.$message.error(`${i.skuName} 装箱数量与发票填写个数不一致`)
            return false
          }
        }
      }

      return true
    },

    async saveWaybill({ status, packingList }) {
      // status == 10 提交待确认
      // status == 20  完成并提交

      // shippingWay
      const invoiceList = []
      let totalPurchasingPrice = 0
      if (this.invoiceInfo.tableData) {
        const table = clone(this.invoiceInfo.tableData)
        const t = table.filter((x) => checkRowsEmpty(x))

        for (const i of t) {
          if (i.sku) {
            if (i.imgUrl) {
              i.imgUrl = i.imgUrl.replace(globalData.fileUrl, '')
            }
            if (i.sellPriceScreenshot) {
              i.sellpriceScreenshot = i.sellPriceScreenshot.replace(
                globalData.fileUrl,
                ''
              )
            }
            if (i.incomeScreenshot) {
              i.incomeScreenshot = i.incomeScreenshot.replace(
                globalData.fileUrl,
                ''
              )
            }
            invoiceList.push(i)
            totalPurchasingPrice += parseInt(i.purchasingPrice)
          }
        }
      }

      const liquidationInvoices = {
        declareValueCurrency:
          this.$refs.invoice.invoiceInfoData.declareValueCurrency,
        liquidationInvoices: invoiceList,
        status: status,
        id: this.id ? parseInt(this.id) : ''
      }

      const packingLists = {
        packingLists: packingList
      }

      const channelFormL = clone(this.channelFormLeft)

      // channelFormL.etInStock =
      //   channelFormL.etInStockDay + ' ' + channelFormL.etInStockTime
      console.log('channelFormL.etInStock :>> ', channelFormL.etInStock)
      // 渠道能力
      channelFormL.channelCapacity =
        this.channelFormLeft.channelCapacity.join(',')
      // 特殊产品
      channelFormL.specialProduct =
        this.channelFormLeft.specialProduct.join(',')
      // 拼接预计入仓时间
      // if (channelFormL.cabinetNumber) {
      //   channelFormL.cabinetInfo =
      //     channelFormL.cabinetNumber + '*' + channelFormL.cabinetType
      // }
      //

      //
      if (channelFormL.deliveryFilesMap) {
        if (Object.values(channelFormL.deliveryFilesMap).length > 0) {
          const arr = []
          for (const k in channelFormL.deliveryFilesMap) {
            arr.push(`${k},${channelFormL.deliveryFilesMap[k]}`)
          }
          channelFormL.deliveryFiles = arr
        }
      }

      // channelFormL.purposeWarehouseType === 700
      if (channelFormL.purposeWarehouseType !== 700) {
        channelFormL.dispatcher = '' // 公司名/个人
        channelFormL.dispatchLinkMan = '' //  联系人
        channelFormL.dispatchPhone = '' //  联系电话
        channelFormL.dispatchEmail = '' //  邮箱
        channelFormL.dispatchProvince = '' //  省
        channelFormL.dispatchCity = '' //  城市
        channelFormL.dispatchZipCode = '' //  邮编
        channelFormL.dispatchAddress = '' //  地址
      } else if (parseFloat(channelFormL.countryId) === 329) {
        const reg1 = /^((\d{5})*(-\d{4})|(\d{5}))$/
        console.log(
          'channelFormL.dispatchZipCode :>> ',
          channelFormL.dispatchZipCode
        )
        console.log(
          'reg1.test(channelFormL.dispatchZipCode) :>> ',
          reg1.test(channelFormL.dispatchZipCode.toString())
        )
        if (!reg1.test(channelFormL.dispatchZipCode.toString())) {
          console.log('11111111111 :>> ', 11111111111)
          this.$message.error('格式错误，美国邮编请填入XXXXX或者XXXXX-XXXX')
          return
        }
      }
      // 清空PVA
      if (
        !(
          this.publicData.countryMap &&
          channelFormL.countryId &&
          this.publicData.countryMap[channelFormL.countryId] &&
          this.publicData.countryMap[channelFormL.countryId].indexOf('英国') !=
            -1 &&
          channelFormL.inStockChannel &&
          channelFormL.isTaxFarming === 0 &&
          [100, 400].includes(channelFormL.purposeWarehouseType)
        )
      ) {
        console.log(' channelFormL.isPVA:>> ', channelFormL.isPVA)
        channelFormL.isPVA = ''
      }

      // superHighValue
      if (!this.channelFormLeft.isBuyInsurance) {
        await this.forcedPurchaseInsurance(channelFormL, totalPurchasingPrice)
      }
      this.$store.dispatch('app/toggleDialog', true)

      console.log('channelFormL :>> ', channelFormL)

      let seaAirWaybillCreate = {}
      const selectedImporterInfo = this.channelFormRight.isVatAndEori
        ? clone(this.selectedImporterInfo)
        : {}
      if (this.createTpye === 'OrderToExpressDelivery') {
        seaAirWaybillCreate = clone(
          Object.assign(
            channelFormL,
            this.channelFormRight,
            liquidationInvoices,
            selectedImporterInfo
          )
        )
      } else {
        seaAirWaybillCreate = clone(
          Object.assign(
            channelFormL,
            this.channelFormRight,
            liquidationInvoices,
            packingLists,
            selectedImporterInfo
          )
        )
      }

      if (this.$route.query.isCopy === '1') {
        this.$delete(seaAirWaybillCreate, 'id')
        for (const s of seaAirWaybillCreate.liquidationInvoices) {
          this.$delete(s, 'id')
          this.$delete(s, 'waybillId')
        }
      }
      console.log('seaAirWaybillCreate :>> ', seaAirWaybillCreate)

      let data = {}
      if (this.orderType === 'quickOrder') {
        data = await saveWaybillFba(seaAirWaybillCreate)
      } else {
        data = await saveWaybillStandard(seaAirWaybillCreate)
      }

      if (data.code === 200) {
        this.$message({
          type: 'success',
          message: '提交成功！'
        })
        this.$router.push({ name: 'WaybillList' })
      } else {
        this.$message.error(data.message)
      }
      this.$store.dispatch('app/toggleDialog', false)
    },

    async uploadFn(file) {
      // 通过 FormData 对象上传文件
      this.$store.dispatch('app/toggleDialog', true)
      var formData = new FormData()
      formData.append('templateFile', file)
      const data = await doImportPackLists(formData)

      if (data.error || data.errorTips) {
        this.$message.error(data.error || data.errorTips)
        this.$store.dispatch('app/toggleDialog', false)
        return false
      }
      if (!data.address) {
        this.$message.error('无派送地址信息！')
        this.$store.dispatch('app/toggleDialog', false)
        return false
      }
      this.customerTotalPackages += data.packingLists.length
      // TODO
      // this.fileList = data
      if (this.address && this.address !== data.address) {
        this.$message.error('派送地址不一致！')
        this.$store.dispatch('app/toggleDialog', false)
        return false
      }
      this.address = data.address
      console.log('data :>> ', data)
      const cf = {
        purposeWarehouseType: 100, //  目的仓库类型
        countryId: data.countryId.toString(), //  国家
        customerTotalPackages: data.currentFileTotalBoxCount || '', // 件数
        dispatchAddressCode: data.shippingFbaStock.fbaCode || '', // 派送地址代码
        dispatcher: data.shippingFbaStock.companyName || '', // 公司名/个人
        dispatchLinkMan: data.shippingFbaStock.contacts || '', //  联系人
        dispatchPhone: data.shippingFbaStock.contactNumber || '', //  联系电话
        dispatchProvince: data.shippingFbaStock.province || '', //  省
        dispatchCity: data.shippingFbaStock.city || '', //  城市
        dispatchZipCode: data.shippingFbaStock.zipCode || '', //  邮编
        dispatchAddress: data.shippingFbaStock.address //  地址
      }
      this.$refs.selectChannelLeftComp.channelform = Object.assign(
        this.$refs.selectChannelLeftComp.channelform,
        cf
      )

      this.$refs.selectChannelLeftComp.channelform.customerTotalPackages =
        this.customerTotalPackages

      // this.$refs.selectChannelLeftComp.retrieveAddress()
      // this.$refs.selectChannelLeftComp.retrieveChannel()

      // 叠加数据
      const waybill = clone(this.invoicesAndPackingLis)
      if (data.liquidationInvoices) {
        waybill.liquidationInvoices = [
          ...(waybill.liquidationInvoices ? waybill.liquidationInvoices : []),
          ...data.liquidationInvoices
        ]
      }
      // console.log('data.packingLists :>> ', data.packingLists)
      // console.log('waybill.packingLists :>> ', waybill.packingLists)
      if (data.packingLists) {
        waybill.packingLists = [
          ...(waybill.packingLists ? waybill.packingLists : []),
          ...data.packingLists
        ]
      }
      this.invoicesAndPackingLis = waybill
      this.sortData(waybill)

      this.$message({
        message: '导入成功！',
        type: 'success'
      })
      this.$store.dispatch('app/toggleDialog', false)
      return true
    },
    async upload(e, index) {
      const file = e.target.files[0] // target事件
      const isEXCEL =
        file.type === 'application/vnd.ms-excel' ||
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

      if (!isEXCEL) {
        this.$message.error('上传文件只能是EXCEL文件!')
        return false
      }

      if (this.fileList[index]) {
        console.log('替换 :>> ')
      }

      // 提交上传
      if (await this.uploadFn(file)) {
        this.fileList[index].file = file
        this.fileList[index].name = file.name
        if (this.fileList.length - 1 === index) {
          this.fileList.push({
            file: '',
            name: ''
          })
        }
      }
    }
  }
}
</script>

<style lang="scss">
#selectChannel {
  .el-card__body {
    padding: 0;
  }
  .el-select {
    width: 100%;
  }
}

.icon-question {
  font-size: 18px;
  margin-left: 10px;
}
.upload-input {
  position: relative;
  display: inline-block;
  background: #d0eeff;
  border: 1px solid #99d3f5;
  border-radius: 4px;
  padding: 4px 12px;
  overflow: hidden;
  color: #1e88c7;
  text-decoration: none;
  text-indent: 0;
  line-height: 20px;
  input {
    position: absolute;
    font-size: 100px;
    right: 0;
    top: 0;
    opacity: 0;
  }
}
</style>
